package future;

import jdk.nashorn.internal.objects.annotations.Getter;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class CompletableFutureMallDemo {
    static List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("dangdangwang"),
            new NetMall("taobao")
    );

    public static List<String> getPrice(List<NetMall> list, String productName) {
        return list.stream().map(netMall ->
             String.format(productName + " in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName))
        ).collect(Collectors.toList());
    }

    public static List<String> getPriceByCompletableFuture(List<NetMall> list, String productName) {
        return list.
                 stream().map(netMall -> CompletableFuture.supplyAsync(()->
                 String.format(productName + " in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName))
                )).collect(Collectors.toList())
                .stream().map(s->s.join()).collect(Collectors.toList());
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        List<String> list1 = getPriceByCompletableFuture(list, "mysql");
        for(String element : list1) {
            System.out.println(element);
        }
        long endTime = System.currentTimeMillis();

        System.out.println("------costTime: " + (endTime - startTime) + " ms");
    }
}

class NetMall {

    private String netMallName;

    public String getNetMallName() {
        return netMallName;
    }

    public NetMall(String netMallName) {
        this.netMallName = netMallName;
    }

    public double calcPrice(String productName) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}